<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:maintenance:add']"
        >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          size="medium"
          @command="(command) => handleImportCommand(command)"
          v-hasPermi="['car:maintenance:export']"
        >
          <el-button plain icon="el-icon-caret-bottom" size="mini"
          >数据导入/导出</el-button
          >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="handleImport" icon="el-icon-upload"
            >数据导入</el-dropdown-item
            >
            <el-dropdown-item command="handleExport" icon="el-icon-download"
            >数据导出</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
        class="el-form-search"
      >
        <el-form-item label="设备编号" prop="plateNumber" class="el-form-search-item">
          <el-input
            v-model="queryParams.plateNumber"
            placeholder="请输入设备编号"
            clearable
            size="mini"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="保养日期" class="el-form-search-item">
          <el-date-picker
            v-model="dateRange"
            size="mini"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="el-form-search-item">
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
          >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
          >
        </el-form-item>
      </el-form>
    </el-row>

    <el-table
      :height="tableHeight"
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
      ref="dataTable"
    >
      <el-table-column label="#" type="index" width="50" align="center">
        <template scope="scope">
          <span>{{
              (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保养时间" align="center" prop="maintenanceTime" width="180" />
      <el-table-column label="设备编号" align="center" prop="plateNumber"  />
      <el-table-column label="保养项目" align="center" prop="name" width="180" />
      <el-table-column label="数量" align="center" prop="number" width="180" />
      <el-table-column label="单价(元)" align="center" prop="price" width="180" />
      <el-table-column label="保养金额(元)" align="center" prop="totalPrice" width="180" />
      <el-table-column label="保养站" align="center" prop="station" width="180" />
      <el-table-column label="部门名称" align="center" prop="deptName" width="180" />
      <el-table-column label="保养说明" align="center" prop="description" width="180" />
      <el-table-column label="公里数" align="center" prop="kilometer" width="180" />
      <el-table-column label="创建人" align="center" prop="createBy" width="180" />

      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="240"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:maintenance:edit']"
          >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:maintenance:remove']"
          >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="viewFiles(scope.row)"
            v-hasPermi="['car:maintenance:export']"
          >查看票据</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改加油票据对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
      v-dialogDrag
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="30">
          <el-col :span="12" >
             <el-form-item label="保养时间" prop="maintenanceTime">
               <el-date-picker
                 v-model="form.maintenanceTime"
                 type="datetime"
                 value-format="yyyy-MM-dd HH:mm:ss"
                 placeholder="选择日期时间"
                 align="right"
                 style="width: 100%"
                 :picker-options="pickerOptions">
               </el-date-picker>
             </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="车牌号" prop="plateNumber">
              <el-input v-model="form.plateNumber" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="保养项目" prop="fuelCard">
              <el-input v-model="form.name" placeholder="请输入保养项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(元)" prop="fuelCard">
              <el-input v-model="form.price" placeholder="请输入单价" />
            </el-form-item></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="数量" prop="station">
              <el-input v-model="form.number" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保养金额" prop="station">
              <el-input v-model="form.totalPrice" placeholder="请输入保养金额" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="保养站" prop="station">
              <el-input v-model="form.station" placeholder="请输入保养站" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公里数" prop="station">
              <el-input v-model="form.kilometer" placeholder="请输入公里数" />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="备注" prop="station">
              <el-input v-model="form.description" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="票据" prop="files">
              <image-upload v-model="form.files" :limit="9" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />
          <div style="display: inline-block; padding-left: 5px">
            是否更新已经存在的数据
          </div>
          <el-button
            type="primary"
            plain
            icon="el-icon-receiving"
            size="mini"
            @click="handleTemplate"
            style="float: right"
          >下载模板</el-button
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看票据" :visible.sync="viewFile.preview" width="400px">
    <image-preview
      :src="viewFile.fileUrls"
      :width="60"
      :height="60"
      v-if="viewFile.num>0"
    />
      <p v-if="viewFile.num>0">
      提示：当前共有{{viewFile.num}}张票据，点击图片进行查看！
      </p>
      <p  v-else>
        提示：当前无票据，请先上传后再进行查看！
      </p>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  add,
  update,
  del
} from "@/api/car/maintenance";
import {getUrlByResourceIdAndResourceType} from  "@/api/system/resource";
import { getToken } from "@/utils/auth";

export default {
  name: "HouseRoom",
  dicts: ["sys_notice_status"],
  components: {},
  data() {
    return {
      //时间选择样式
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      viewFile:{
        fileUrls:'',
        num:'',
        preview:false,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/car/fuels/import?type=MAINTENANCE",
      },
      // 表格高度
      tableHeight: document.documentElement.clientHeight - 180,
      // 遮罩层
      loading: true,
      // 选中id数组
      ids: [],
      //评价列表查询的id
      checkid: null,
      // 选中行数组
      selection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示更多搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 数据详情表格数据
      dataList: [],
      // 数据小区表格数据
      houseVillageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: 'MAINTENANCE',
        orderByColumn: "create_time",
        isAsc: "desc",
        endTime: null,
        beginTime: null,
        plateNumber: null,
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        maintenanceTime: [{ required: true, message: "保养时间不能为空", trigger: "blur" }],
        plateNumber: [{ required: true, message: "车牌号不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    /** 查询数据详情列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then((response) => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: 'MAINTENANCE',
        maintenanceTime: null,
        plateNumber: null,
        name: null,
        price: null,
        number: null,
        totalPrice: null,
        driverId: null,
        driverName: null,
        deptId: null,
        deptName: null,
        kilometer: null,
        station: null,
        description: null,
        files:null
      };
      this.featureList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.resetForm("queryMoreForm");
      this.handleQuery();
    },
    /** 更多搜索按钮 */
    handleMoreQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.$refs.drawer.closeDrawer();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selection = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row;
      this.open = true;
      this.title = "修改";
      getUrlByResourceIdAndResourceType(row.id,'CarMaintenance').then((response) => {
        this.form.files = response.msg;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            update(this.form.id,this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除记录？")
        .then(function () {
          return del(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    viewFiles(row) {
      this.viewFile.preview=true;
      getUrlByResourceIdAndResourceType(row.id,'CarMaintenance').then((response) => {
        this.viewFile.fileUrls = response.msg;
        this.viewFile.num=response.msg.length>0?response.msg.split(",").length:0;
      });
    },
    /** 导入 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板 */
    handleTemplate() {
      this.download(
        "car/maintenances/template",
        {
          ...this.queryParams,
        },
        `保养数据导入模板.xlsx`
      );
    },
    /** 导出按钮 */
    handleExport() {
      this.$confirm("确认导出数据数据吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.download(
          "/car/maintenances/export",
          {
            ...this.queryParams,
          },
          `车辆保养_${new Date().getTime()}.xlsx`
        );
      });
    },
    // 导入操作触发
    handleImportCommand(command) {
      switch (command) {
        case "handleImport":
          this.handleImport();
          break;
        case "handleTemplate":
          this.handleTemplate();
          break;
        case "handleExport":
          this.handleExport();
          break;
        default:
          break;
      }
    },
    // 重新绘制表格，防止抖动与滚动条异常
    setDataTable() {
      this.$nextTick(() => {
        this.$refs.dataTable.doLayout();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.drawer_content {
  margin: 0 30px;
  .drawer_footer {
    float: right;
    padding-bottom: 40rpx;
  }
}
</style>
